<template>
  <div>
    <el-container style="flex-wrap: wrap">
      <!-- 头部导航栏 -->
      <BreadHeader></BreadHeader>
      <XPannel>
        <!-- 卡片头部 -->
        <template v-slot:header>
          <span>角色管理</span>
          <el-button
            type="primary"
            style="float: right; padding: 10px 20px; margin-left: 15px"
            @click="draweradd = true"
            >添加角色</el-button
          >
          <el-dialog
            title="添加角色"
            :visible.sync="draweradd"
            width="30%"
            style="text-align: center"
          >
            <el-form
              :model="addruleForm"
              :rules="rulesadd"
              ref="addruleForm"
              label-width="90px"
              class="demo-ruleForm"
            >
              <el-form-item
                label="角色名称"
                prop="addname"
                style="width: 80%; margin: 20px auto"
              >
                <el-input
                  placeholder="请输入角色名称"
                  v-model="addruleForm.addname"
                  clearable
                  style="width: 270px; display: block"
                >
                </el-input>
              </el-form-item>
              <el-form-item
                label="角色描述"
                prop="adddescription"
                style="width: 80%; margin: 20px auto"
              >
                <el-input
                  placeholder="请输入角色描述"
                  v-model="addruleForm.adddescription"
                  clearable
                  style="width: 270px; display: block"
                >
                </el-input>
              </el-form-item>
              <el-form-item
                label="创建时间"
                prop="created_at"
                style="width: 80%; margin: 20px auto"
              >
                <el-date-picker
                  v-model="addruleForm.created_at"
                  type="datetime"
                  placeholder="选择角色创建日期时间"
                  align="right"
                  :picker-options="pickerOptions"
                  style="width: 270px; display: block"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item
                label="修改时间"
                prop="updated_at"
                style="width: 80%; margin: 20px auto"
              >
                <el-date-picker
                  v-model="addruleForm.updated_at"
                  type="datetime"
                  placeholder="选择角色修改日期时间"
                  align="right"
                  :picker-options="pickerOptions"
                  style="width: 270px; display: block"
                >
                </el-date-picker>
              </el-form-item>
            </el-form>
            <!-- 对话框底部 -->
            <div slot="footer" class="dialog-footer">
              <el-button
                @click="draweradd = false"
                style="padding: 10px 20px; margin-right: 1px"
                >取 消</el-button
              >
              <el-button
                type="primary"
                @click="addrole('addruleForm')"
                style="padding: 10px 20px"
                >确 定</el-button
              >
              <el-button
                type="info"
                @click="resetForm('addruleForm')"
                style="padding: 10px 20px"
                >重置</el-button
              >
            </div>
          </el-dialog>
          <!-- </el-drawer> -->
        </template>
        <!-- 卡片身体 -->
        <template v-slot:default>
          <el-row style="margin: 5px 0">
            <el-col :span="1.8" style="padding: 0 0">
              <template>
                <p style="color: #303133; font-size: 16px; line-height: 40px">
                  搜索栏：
                </p>
              </template>
            </el-col>
            <el-col :span="4" style="padding: 0 0; margin: 0 10px">
              <el-input
                placeholder="请输入角色名称"
                v-model="searchname"
                clearable
              >
              </el-input>
            </el-col>
            <el-col :span="4" style="padding: 0 0">
              <el-input
                placeholder="请输入角色描述"
                v-model="searchdescription"
                clearable
              >
              </el-input>
            </el-col>
            <!-- <el-col :span="4" style="padding: 0 0; margin-left: 10px">
              <el-date-picker
                v-model="searchcreated_at"
                type="datetime"
                placeholder="选择角色创建日期时间"
                align="right"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-col> -->
            <!-- <el-col :span="4" style="padding: 0 0">
              <el-date-picker
                v-model="searchupdated_at"
                type="datetime"
                placeholder="选择角色修改日期时间"
                align="right"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-col> -->
            <el-col :span="2" style="margin-left: 15px">
              <el-button
                type="primary"
                @click="searchroles"
                style="padding: 12px 15px"
              >
                <i class="el-icon-search"></i>搜索
              </el-button>
            </el-col>
          </el-row>
          <el-table
            :data="list_data"
            @selection-change="handleSelectionChange"
            ref="multipleTable"
            height="450"
            border
            style="width: 100%; margin: 20px auto"
          >
            <el-table-column label="全选" type="selection" width="55">
            </el-table-column>
            <el-table-column prop="id" label="ID" width="100">
            </el-table-column>
            <el-table-column prop="name" label="角色名称" width="200">
            </el-table-column>
            <el-table-column prop="description" label="角色描述" width="180">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="xiugaiobtain(scope.row)"
                  type="primary"
                  style="margin-left: 16px; padding: 5px 10px"
                >
                  <i class="el-icon-edit"></i>
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  @click="open(scope.row)"
                  style="padding: 5px 10px"
                >
                  <i class="el-icon-delete"></i>
                  删除
                </el-button>
                <el-button
                  @click="allocation(scope)"
                  type="warning"
                  style="margin-left: 16px; padding: 5px 10px"
                >
                  <i class="el-icon-setting"></i>
                  分配权限
                </el-button>
                <!-- 修改弹窗区--抽屉 -->
                <el-drawer
                  title="角色修改区"
                  :visible.sync="drawer"
                  :show-close="true"
                >
                  <el-form
                    :model="edutruleForm"
                    :rules="rulesedit"
                    ref="edutruleForm"
                    label-width="100px"
                    class="demo-ruleForm"
                    style="text-align: center"
                  >
                    <el-form-item
                      label="角色名称"
                      prop="namesave"
                      style="margin: 20px; width: 80%; margin: 15px auto"
                    >
                      <el-input
                        placeholder="请输入角色名称"
                        v-model="edutruleForm.namesave"
                        clearable
                        style="width: 300px; display: block"
                      >
                      </el-input>
                    </el-form-item>
                    <el-form-item
                      label="角色描述"
                      prop="descriptionsave"
                      style="margin: 20px; width: 80%; margin: 15px auto"
                    >
                      <el-input
                        placeholder="请输入角色描述"
                        v-model="edutruleForm.descriptionsave"
                        clearable
                        style="width: 300px; display: block"
                      >
                      </el-input>
                    </el-form-item>
                    <el-form-item
                      label="创建日期"
                      prop="created_atsave"
                      style="margin: 20px; width: 80%; margin: 15px auto"
                    >
                      <el-date-picker
                        v-model="edutruleForm.created_atsave"
                        type="datetime"
                        placeholder="选择角色创建日期时间"
                        align="right"
                        :picker-options="pickerOptions"
                        style="width: 300px; display: block"
                      >
                      </el-date-picker>
                    </el-form-item>
                    <el-form-item
                      label="修改日期"
                      prop="updated_atsave"
                      style="margin: 20px; width: 80%; margin: 15px auto"
                    >
                      <el-date-picker
                        v-model="edutruleForm.updated_atsave"
                        type="datetime"
                        placeholder="选择角色修改日期时间"
                        align="right"
                        :picker-options="pickerOptions"
                        style="width: 300px; display: block"
                      >
                      </el-date-picker>
                    </el-form-item>
                    <el-button
                      type="success"
                      @click="submit('edutruleForm')"
                      style="padding: 10px 20px; margin: 5px"
                      >确认修改</el-button
                    >
                    <el-button
                      type="info"
                      @click="reset('edutruleForm')"
                      style="padding: 10px 20px; margin: 5px"
                      >重置已填</el-button
                    >
                  </el-form>
                </el-drawer>
                <!-- 分配权限--对话框 -->
                <el-dialog
                  title="分配权限"
                  :visible.sync="drawerallocation"
                  width="30%"
                >
                  <el-form
                    :model="allocationruleForm"
                    :rules="rulesallocation"
                    ref="allocationruleForm"
                    label-width="100px"
                    class="demo-ruleForm"
                  >
                    <el-form-item label="角色名称:" prop="allocation_role_name">
                      <span>{{ allocationruleForm.allocation_role_name }}</span>
                      <!-- <el-input
                        v-model.number="allocationruleForm.allocation_role_name"
                      ></el-input> -->
                    </el-form-item>
                    <el-form-item label="角色ID:" prop="allocation_role_id">
                      <span>{{ allocationruleForm.allocation_role_id }}</span>

                      <!-- <el-input
                        v-model.number="allocationruleForm.allocation_role_id"
                      ></el-input> -->
                    </el-form-item>
                    <el-form-item label="选择权限" prop="allocations">
                      <el-input
                        v-model="allocationruleForm.allocations"
                        placeholder="请输入权限名"
                        @change="allocation_search_fun"
                      ></el-input>
                    </el-form-item>

                    <!-- 列表--权限 -->
                    <!-- :row-key="(row) => row.id" -->
                    <el-table
                      ref="multipleTable"
                      border
                      style="width: 100%; margin: 20px auto"
                      :data="allocation_list"
                      :row-key="getRowKey"
                      @selection-change="handleSelectionChange_allocation"
                      @select="colSelected"
                    >
                      <el-table-column
                        label="全选"
                        type="selection"
                        width="55"
                        :reserve-selection="true"
                      >
                      </el-table-column>
                      <el-table-column prop="name" label="权限名称" width="100">
                      </el-table-column>
                      <el-table-column prop="father" label="父级" width="120">
                      </el-table-column>
                      <el-table-column prop="description" label="权限说明">
                      </el-table-column>
                    </el-table>

                    <!-- 页码 -->
                    <div class="block" style="max-width: 600px; margin: auto">
                      <el-pagination
                        :page-sizes="[5, 10, 15, 20]"
                        :page-size="allocation_pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="allocation_totalUsers"
                        @size-change="handleChangeSize_allocation"
                        @current-change="handleCurrentChange_allocation"
                      >
                      </el-pagination>
                    </div>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button
                      type="primary"
                      @click="allocationrole()"
                      style="padding: 10px 20px; margin: 10px"
                      >保 存</el-button
                    >
                    <el-button
                      @click="drawerallocation = false"
                      style="padding: 10px 20px; margin: 10px"
                      >取 消</el-button
                    >
                  </div>
                </el-dialog>
              </template>
            </el-table-column>
          </el-table>
          <!-- 批量操作 -->
          <div class="piliang" style="width: 95%">
            <el-button
              type="danger"
              @click="batchDelete"
              style="padding: 10px 10px"
              >批量删除</el-button
            >
            <el-button
              @click="toggleSelection()"
              type="primary"
              style="padding: 10px 10px"
              >取消选择</el-button
            >
          </div>
          <!-- 页码--主页 -->
          <div class="block" style="max-width: 600px; margin: auto">
            <el-pagination
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total_roles"
              @size-change="handleChangeSize"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </template>
      </XPannel>
    </el-container>
  </div>
</template>

<script>
// import http from '@/api/http';
import http from "@/api/http";
import BreadHeader from "@/components/BreadHeader.vue";
import XPannel from "@/components/XPannel.vue";
import { mapState } from "vuex";

export default {
  components: {
    XPannel,
    BreadHeader,
  },
  computed: {
    // ...mapState(["name","picture","SelectList"]),
    ...mapState(["name", "picture"]),
    ...mapState({
      permission_id: (state) => state.permission_id,
      allocations_vuex: (state) => state.allocations_vuex,
    }),
    userName() {
      return this.name;
    },
    userPicture() {
      return this.picture;
    },
    // SelectList(){
    //   return this.SelectList;
    // },
    uniqueArray() {
      const unique = new Set(this.selected_allocation_id);
      return [...unique];
    },
    // selectdIds(){
    //   return this.allocationruleForm?.allocations.join(",")
    // }
  },
  data() {
    // 账号规范
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("账号不能为空！"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值！"));
        } else {
          if (value > this.total_roles) {
            callback(new Error("当前无此角色！"));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    return {
      draweradd: false, //对话框--添加
      drawerallocation: false, //对话框--分配权限
      // 添加角色的数据和规范
      addruleForm: {
        addname: "",
        adddescription: "",
        created_at: "",
        updated_at: "",
      },
      rulesadd: {
        addname: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        adddescription: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 2, message: "长度应大于2个字符", trigger: "blur" },
        ],
        created_at: [
          // 时间例子：2024-10-10 12:00:00
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        updated_at: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
      },
      // 分配权限的数据和规范
      allocationruleForm: {
        // 分配的角色信息
        allocation_role_name: "",
        allocation_role_id: "",
        allocations: '',
      },
      rulesallocation: {
        allocation_role: [{ validator: checkAge, trigger: "blur" }],
      },
      searchname: "",
      searchdescription: "",
      searchcreated_at: "",
      searchupdated_at: "",
      list_data: [],
      totalUsers: 0, //总数
      pageSize: 5, //每页条数
      pageNum: 1, //当前页码
      allocation_totalUsers: 0, //总数
      allocation_pageSize: 5, //每页条数
      allocation_pageNum: 1, //当前页码
      total_roles: null,
      delroleid: null,
      drawer: false,
      xiugaiobtainuid: null,
      edutruleForm: {
        namesave: "",
        descriptionsave: "",
        created_atsave: "",
        updated_atsave: "",
      },
      rulesedit: {
        namesave: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        descriptionsave: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 2, message: "长度应大于2个字符", trigger: "blur" },
        ],
        created_atsave: [
          // 时间例子：2024-10-10 12:00:00
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        updated_atsave: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      allocation_list: [], //权限表列表
      selected: [],
      selected_allocation_id: [],
      allocation_index: null,
      permission_id_vuex: null,
      arr_selected_vuex: [],
      // 选中的权限数据
      SelectedAllocation: [],
      checkRow: [], //选中的对象
    };
  },
  methods: {
    getRowKey(row) {
      console.log(row);
      return row.id;
    },
    selectRowById(specificIds) {
      // 确保传入的是一个数组
      if (!Array.isArray(specificIds)) {
        console.error("传入的参数需要是一个数组");
        return;
      }
      // 遍历 ID 数组，找到对应的行数据并勾选
      specificIds.forEach((id) => {
        const row = this.allocation_list.find(
          (item) => item.id === parseInt(id)
        );
        if (row) {
          // 使用 toggleRowSelection 方法勾选对应的行
          this.$refs.multipleTable.toggleRowSelection(row, true);
        }
      });
    },
    // 添加接口
    addrole() {
      http
        .post("/permission/roles_add", {
          name: this.addruleForm.addname,
          description: this.addruleForm.adddescription,
          created_at: this.addruleForm.created_at,
          updated_at: this.addruleForm.updated_at,
        })
        .then((response) => {
          console.log(response);
          this.$message({
            message: "恭喜你，角色信息添加成功！",
            type: "success",
          });
          this.listfun();
          this.draweradd = false;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 保存设置--权限支配--ing
    allocationrole() {
      http
        .post("/permission/permissions_dominate", {
          allocation_role: this.allocationruleForm.allocation_role_id,
          allocations: this.allocationruleForm.allocations,
        })
        .then((response) => {
          if (response.code == 0) {
            this.$message({
              message: response.msg,
              type: "success",
            });
          }
          console.log(response);
          this.drawerallocation = false;
          this.allocationruleForm.allocations = '';
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 添加弹窗重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    reset(formName) {
      this.$refs[formName].resetFields();
    },
    // 搜索按钮及接口
    searchroles() {
      http
        .get("/permission/roles_search", {
          params: {
            name: this.searchname.replace(/\s+/g, ""),
            description: this.searchdescription.replace(/\s+/g, ""),
            created_at: this.searchcreated_at,
            updated_at: this.searchupdated_at,
            page: this.pageNum,
            page_size: this.pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          this.list_data = response.data;
          this.total_roles = response.total;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 列表方法及接口
    listfun() {
      http
        .get("/permission/roles_list", {
          params: {
            page: this.pageNum,
            page_size: this.pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          this.list_data = response.data.list;
          this.total_roles = response.data.totalNum;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleSelectionChange(val) {
      this.selected = val;
      console.log(this.selected);
    },
    // 页码设置
    handleChangeSize(data) {
      this.pageSize = data;
      const isSearchnameDefault = this.searchname === "";
      const isSearchdescriptionDefault = this.searchdescription === "";

      if (isSearchnameDefault && isSearchdescriptionDefault) {
        // 如果所有字段都是初始值，则调用listfun
        this.listfun();
      } else {
        // 否则，调用searchroles
        this.searchroles();
      }
    },
    handleChangeSize_allocation(data) {
      this.allocation_pageSize = data;
      this.allocation_list_fun();
    },
    handleCurrentChange(data) {
      this.pageNum = data;
      const isSearchnameDefault = this.searchname === "";
      const isSearchdescriptionDefault = this.searchdescription === "";

      if (isSearchnameDefault && isSearchdescriptionDefault) {
        // 如果所有字段都是初始值，则调用listfun
        this.listfun();
      } else {
        // 否则，调用searchroles
        this.searchroles();
      }
    },
    // 权限--页码设置
    handleCurrentChange_allocation(data) {
      this.allocation_pageNum = data;
      this.allocation_list_fun();
    },
    // 单个删除
    open(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(1, row);
          // this.delroleid = this.userlist[row].id
          this.delroleid = row.id;
          this.deleterolefn();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.listfun();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配权限
    allocation(scope) {
      http
        .get("/permission/have_permissions/" + scope.row.id)
        .then((response) => {
          console.log("已有权限：", response);
          this.$message({
            message: response.msg,
            type: "warning",
          });
          this.allocationruleForm.allocations = response.data.permission_id||[];

          this.selectRowById(this.allocationruleForm.allocations.split(','));
          // this.allocationruleForm.allocations.push(response.data.permission_id);
          // this.selectRowById(this.allocationruleForm.allocations);
        })
        .catch((error) => {
          console.log(error);
        });
      console.log(scope);
      this.drawerallocation = true;
      this.allocationruleForm.allocation_role_id = scope.row.id;
      this.allocationruleForm.allocation_role_name = scope.row.name;
      let index = scope.$index + 1;
      this.allocation_index = index;
    },
    // 单个删除-接口
    deleterolefn() {
      http
        .get("/permission/roles_delete/" + this.delroleid)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 修改--获取数据
    xiugaiobtain(row) {
      this.drawer = true;
      console.log(row.id);
      let editid = row.id;
      http
        .get("permission/roles_users_edit/" + editid)
        .then((response) => {
          console.log(response);
          this.xiugaiobtainuid = response.data[0].id;
          this.edutruleForm.namesave = response.data[0].name;
          this.edutruleForm.descriptionsave = response.data[0].description;
          let date_craeted = new Date(response.data[0].created_at);
          let date_updated = new Date(response.data[0].created_at);
          this.edutruleForm.created_atsave = date_craeted;
          this.edutruleForm.updated_atsave = date_updated;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 修改--保存数据
    submit(edutruleForm) {
      this.$refs[edutruleForm].validate((valid) => {
        if (valid) {
          this.$message({
            message: "恭喜你，角色信息修改成功！",
            type: "success",
          });
          http
            .post("permission/roles_save_edit/" + this.xiugaiobtainuid, {
              name: this.edutruleForm.namesave,
              description: this.edutruleForm.descriptionsave,
              created_at: this.edutruleForm.created_atsave,
              updated_at: this.edutruleForm.updated_atsave,
            })
            .then((response) => {
              console.log(response);
              this.listfun();
              this.drawer = false;
            })
            .catch((error) => {
              console.log(error);
            });
          this.drawer = false;
        } else {
          console.log("修改失败!!");
          return false;
        }
      });
    },
    // 批量删除+接口
    batchDelete() {
      if (this.selected.length === 0) {
        this.$message({
          message: "请先选择要删除的项",
          type: "warning",
        });
        return;
      }
      this.$confirm("此操作将永久删除选中的角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 批量删除---代办--ok
          this.selected.forEach((item) => {
            // const index = this.userlist.indexOf(item);
            let deluserids = [];
            deluserids.push(item.id);
            let deluseridsting = JSON.stringify(deluserids);
            http
              .get("/permission/roles_deletes/" + deluseridsting)
              .then((response) => {
                console.log(response);
              })
              .catch((error) => {
                console.log(error);
              });
            this.listfun();
            // this.userlist.splice(index, 1);
          });
          this.selected = []; // 清空选中的项
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批量取消方法
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 权限列表方法+接口
    allocation_list_fun() {
      http
        .get("permission/permissions_list", {
          params: {
            page: this.allocation_pageNum,
            page_size: this.allocation_pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          this.allocation_list = response.data.list;
          this.allocation_totalUsers = response.data.totalNum;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 权限列表的搜索查询
    allocation_search_fun() {
      http
        .get("/permission/permissions_search", {
          params: {
            name: this.allocationruleForm.allocations,
          },
        })
        .then((response) => {
          console.log(response);
          this.allocation_list = response.data;
          this.allocationruleForm.allocations = "";
          // this.allocationruleForm.allocations = [];
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // vuex中的方法
    // 表格全选事件
    handleSelectionChange_allocation(val) {
      console.log("复选框：checkbox:", val);
      this.checkRow = val;
      let ids = val.map((item) => item.id);
      this.allocationruleForm.allocations = JSON.stringify(ids);

      // this.allocationruleForm.allocations.push(ids);
      console.log("复选框-id 01：", ids);
    },
    colSelected(m, n) {
      console.log("单击了 checkbox:", m, n);
      this.checkRow = m;

      let ids = m.map((item) => item.id);
      this.allocationruleForm.allocations = JSON.stringify(ids);
      // this.allocationruleForm.allocations.push(ids);
      console.log("复选框-id 02：", ids);
    },

    // selectRowsByIds(ids) {
    //   // 假设你的数据列表中的每个对象都有一个唯一的 id 属性
    //   this.allocation_list.forEach(row => {
    //     if (ids.includes(row.id)) {
    //       this.$refs.multipleTable.toggleRowSelection(row, true);
    //     }
    //   });
    // },
    // 勾选中单选框
    toggleSelection_quanxian(rows) {
      // [tableData[1], tableData[2]]
      // rows:[1,2,3,4]
      var arr = [];
      for (let i = 0; i < rows.length; i++) {
        arr.push(`allocation_list[${[i]}]`);
      }

      arr.map((item) => {
        // 使用正则表达式去除引号
        return item.replace(/['"]/g, "");
      });
      let new_arr = arr.map((item) => {
        // 使用正则表达式去除引号
        return item.replace(/['"]/g, "");
      });
      console.log(new_arr);
      console.log(arr);
      if (arr) {
        arr.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
  },
  created() {
    this.listfun();
    this.allocation_list_fun();

    // this.selectRowsByIds(this.SelectList);
  },

  // watch: {
  //   selected_allocation_id() {
  //     // 将数组转换为字符串，并赋值给 allocationruleForm.allocations
  //     // 如果 allocationruleForm.allocations 需要是一个数组，就不要使用 toString 或 join
  //     this.allocationruleForm.allocations = this.uniqueArray.join(",");
  //   },
  // },
};
</script>

<style scoped>
.el-form-item {
  margin-bottom: 5px;
}
</style>